import { createRouter, createWebHistory } from 'vue-router';
import { saveFromRouter } from '@/util/utils';

const routes = [
  {
    path: '/',
    name: '首页',
    redirect: '/service/send'
  },
  {
    path: '/service',
    component: () => import('@/components/layout'),
    redirect: '/service/send',
    children: [
      {
        path: '/service/send',
        name: '信息发布',
        component: () => import('@/views/send')
        // meta: {
        //   keepAlive: true
        // }
      },
      {
        path: '/service/record',
        name: '历史发布',
        component: () => import('@/views/record')
        // meta: {
        //   keepAlive: true
        // }
      },
      {
        path: '/service/devices',
        name: '设备列表',
        component: () => import('@/views/devices')
        // meta: {
        //   keepAlive: true
        // }
      }
    ]
  },
  {
    path: '/post-message',
    component: () => import('@/components/layout/post-message'),
    redirect: '/post-message/imgAndVideo',
    children: [
      // 发布文章
      {
        path: 'article',
        component: () => import('@/views/article')
      },
      // 文档
      {
        path: 'file',
        component: () => import('@/views/file')
      },
      // 图像
      {
        path: 'imgAndVideo',
        component: () => import('@/views/imgAndVideo')
      }
    ]
  },
  {
    path: '/position',
    name: '发布位置',
    // meta: {
    //   keepAlive: true
    // },
    component: () => import('@/views/positon')
  },
  {
    path: '/device-details',
    component: () => import('@/views/devices/list/device-details')
  },
  {
    path: '/schedule',
    component: () => import('@/views/devices/list/schedule')
  },
  {
    path: '/article-details',
    component: () => import('@/views/record/details')
  }
];

export function setupRouter() {
  const base = window.__MICRO_APP_BASE_ROUTE__ || process.env.BASE_URL;
  const history = createWebHistory(base);
  const router = createRouter({
    history,
    routes
  });
  if (window.__MICRO_APP_ENVIRONMENT__) {
    router.beforeEach((to, from) => {
      // 记录上一页路由，解决go(-1)在基座里面无效的问题
      saveFromRouter(to, from);

      if (window.history.state?.current) {
        window.history.state.current = `/`;
      }
    });
    router.afterEach(() => {
      if (typeof window.history.state === 'object') {
        const _baseRoute = window.__MICRO_APP_BASE_ROUTE__;
        window.history.state.current = `/${_baseRoute.slice(_baseRoute.indexOf('microapp'))}`;
      }
    });
  }
  return {
    history,
    router
  };
}
